import os
from pathlib import Path
from typing import Dict, List


class Config:
    """Central configuration for the voice control app."""

    # LLM (Doubao) configuration
    DOUBAO_API_KEY: str = os.environ.get("DOUBAO_API_KEY", "b19a627f-a048-4e5f-b291-938801933471")
    DOUBAO_API_URL: str = os.environ.get("DOUBAO_API_URL", "https://ark.cn-beijing.volces.com/api/v3/chat/completions")  # e.g. set via env
    DOUBAO_MODEL: str = os.environ.get("DOUBAO_MODEL", "doubao-seed-1-6-251015")

    # Whisper ASR configuration
    WHISPER_MODEL: str = os.environ.get("WHISPER_MODEL", "base")
    # ASR enhancements
    ASR_LANGUAGE: str = os.environ.get("ASR_LANGUAGE", "zh")
    ASR_INITIAL_PROMPT_SEED: str = os.environ.get(
        "ASR_INITIAL_PROMPT_SEED",
        "以下为中文语音助手指令，包含常见应用、人名与站点：",
    )
    # 热词：可根据你的使用场景增删
    ASR_HOTWORDS: List[str] = [
        "周星驰",
        "浏览器",
        "百度",
        "第一条链接",
        "记事本",
        "计算器",
        "资源管理器",
        "静音",
        "取消静音",
    ]
    # 纠错映射：针对常见误识别进行替换
    ASR_CORRECTIONS: Dict[str, str] = {
        "周用词": "周星驰",
    }

    # TTS configuration
    TTS_MODEL: str = os.environ.get(
        "TTS_MODEL",
        "tts_models/zh-CN/baker/tacotron2-DDC_ph",
    )

    # Audio and output paths
    AUDIO_DIR: Path = Path("data") / "audio"
    OUTPUT_DIR: Path = Path("output")
    APP_PATH_CACHE_FILE: Path = OUTPUT_DIR / "app_paths.json"

    # Default save directory keyword or absolute path
    # Supported values: "Desktop", "Documents", "E:/" or any absolute path
    DEFAULT_SAVE_DIR: str = os.environ.get("DEFAULT_SAVE_DIR", "E:/")

    # Microphone settings
    MIC_SAMPLE_RATE: int = int(os.environ.get("MIC_SAMPLE_RATE", "16000"))
    MIC_CHANNELS: int = int(os.environ.get("MIC_CHANNELS", "1"))
    # Max duration for pet interaction recording (seconds)
    INTERACTION_MAX_DURATION: float = float(os.environ.get("INTERACTION_MAX_DURATION", "15.0"))

    # Search engine preference for web actions (baidu|bing)
    SEARCH_ENGINE: str = os.environ.get("SEARCH_ENGINE", "baidu").lower()
    if SEARCH_ENGINE not in ("baidu", "bing"):
        SEARCH_ENGINE = "baidu"

    # App aliases (Windows built-ins and common apps)
    APP_ALIASES: Dict[str, str] = {
        # 系统与常见工具
        "记事本": "notepad.exe",
        "Notepad": "notepad.exe",
        # 容错：常见近音误识统一映射到记事本
        "即时本": "notepad.exe",
        "祭祀本": "notepad.exe",
        "计师本": "notepad.exe",
        "纪事本": "notepad.exe",

        "计算器": "calc.exe",
        "Calculator": "calc.exe",
        "画图": "mspaint.exe",
        "Paint": "mspaint.exe",
        "资源管理器": "explorer.exe",
        "文件管理器": "explorer.exe",
        "命令提示符": "cmd.exe",
        "PowerShell": "powershell.exe",
        "终端": "powershell.exe",

        # 浏览器
        "浏览器": "msedge.exe",  # 默认尝试 Edge
        "Edge": "msedge.exe",
        "微软Edge": "msedge.exe",
        "Chrome": "chrome.exe",
        "谷歌浏览器": "chrome.exe",

        # 聊天与办公
        # 微信（根据你的环境使用 Weixin.exe；保留 WeChat 兼容）
        "微信": "Weixin.exe",
        "Weixin": "Weixin.exe",
        "WeChat": "WeChat.exe",
        # 企业微信
        "企业微信": "WeCom.exe",
        "WeCom": "WeCom.exe",
        # QQ
        "QQ": "QQ.exe",
        # 钉钉
        "钉钉": "DingTalk.exe",
        "DingTalk": "DingTalk.exe",

        # WPS 套件及子应用（提高命中率）
        "WPS": "suite:wps",
        "WPS Office": "suite:wps",
        "金山": "suite:wps",
        "金山办公": "suite:wps",
        "WPS套件": "suite:wps",
        "WPS 文字": "wps.exe",
        "WPS文字": "wps.exe",
        "Writer": "wps.exe",
        "WPS 表格": "et.exe",
        "WPS表格": "et.exe",
        "ET": "et.exe",
        "WPS 演示": "wpp.exe",
        "WPS演示": "wpp.exe",
        "WPP": "wpp.exe",

        # Microsoft Office
        "Word": "WINWORD.EXE",
        "Excel": "EXCEL.EXE",
        "PowerPoint": "POWERPNT.EXE",
    }

    # 新增：窗口标题关键词映射（窗口层匹配）
    APP_WINDOW_KEYWORDS: Dict[str, List[str]] = {
        # 套件级：覆盖所有子应用常见窗口标题
        "WPS": ["WPS", "WPS 文字", "WPS 表格", "WPS 演示"],
        "WPS Office": ["WPS", "WPS 文字", "WPS 表格", "WPS 演示"],
        "金山": ["WPS", "WPS 文字", "WPS 表格", "WPS 演示"],
        "金山办公": ["WPS", "WPS 文字", "WPS 表格", "WPS 演示"],
        "WPS套件": ["WPS", "WPS 文字", "WPS 表格", "WPS 演示"],

        # 子应用级
        "wps.exe": ["WPS 文字", "WPS"],
        "et.exe": ["WPS 表格", "WPS"],
        "wpp.exe": ["WPS 演示", "WPS"],

        # 系统与工具
        "notepad.exe": ["记事本", "Notepad"],
        "calc.exe": ["计算器", "Calculator"],
        "mspaint.exe": ["画图", "Paint"],
        "explorer.exe": ["文件资源管理器", "Windows 资源管理器", "资源管理器"],
        "cmd.exe": ["命令提示符"],
        "powershell.exe": ["Windows PowerShell", "PowerShell"],

        # 浏览器（可作为补充）
        "浏览器": ["Microsoft Edge", "Edge", "浏览器"],
        "msedge.exe": ["Microsoft Edge", "Edge", "浏览器"],
        "Edge": ["Microsoft Edge", "Edge"],
        "chrome.exe": ["Google Chrome", "Chrome", "谷歌浏览器"],

        # 微信与常用 IM
        "微信": ["微信", "WeChat"],
        "Weixin.exe": ["微信", "WeChat"],
        "WeChat.exe": ["微信", "WeChat"],
        "WeCom.exe": ["企业微信", "WeCom"],
        "QQ.exe": ["QQ"],
        "DingTalk.exe": ["钉钉", "DingTalk"],

        # Office
        "WINWORD.EXE": ["Word", "Microsoft Word"],
        "EXCEL.EXE": ["Excel", "Microsoft Excel"],
        "POWERPNT.EXE": ["PowerPoint", "Microsoft PowerPoint"],
    }

    # 是否允许全盘扫描定位可执行文件（高权限与高开销）
    ENABLE_FULL_DRIVE_SCAN: bool = True

    # 增加：全盘扫描详细日志开关（显示进度）
    FULL_DRIVE_SCAN_VERBOSE: bool = True

    # 应用预设流程：打开后自动执行的动作序列
    APP_PRESET_ACTIONS: Dict[str, List[Dict[str, str]]] = {
        # 微信：打开后自动聚焦搜索框（若支持）或置顶
        "Weixin.exe": [
            {"type": "system", "op": "focus_window", "target": "微信"},
        ],
        "WeChat.exe": [
            {"type": "system", "op": "focus_window", "target": "微信"},
        ],
        # 企业微信
        "WeCom.exe": [
            {"type": "system", "op": "focus_window", "target": "企业微信"},
        ],
        # QQ
        "QQ.exe": [
            {"type": "system", "op": "focus_window", "target": "QQ"},
        ],
        # 钉钉
        "DingTalk.exe": [
            {"type": "system", "op": "focus_window", "target": "钉钉"},
        ],
        # 浏览器：打开后置顶，便于后续自动化
        "msedge.exe": [
            {"type": "system", "op": "focus_window", "target": "Edge"},
        ],
        "chrome.exe": [
            {"type": "system", "op": "focus_window", "target": "Chrome"},
        ],
        # Office：置顶对应窗口
        "WINWORD.EXE": [
            {"type": "system", "op": "focus_window", "target": "Word"},
        ],
        "EXCEL.EXE": [
            {"type": "system", "op": "focus_window", "target": "Excel"},
        ],
        "POWERPNT.EXE": [
            {"type": "system", "op": "focus_window", "target": "PowerPoint"},
        ],
    }
    # Approval and dialog settings
    REQUIRE_APPROVAL: bool = bool(int(os.environ.get("REQUIRE_APPROVAL", "0")))
    DIALOG_MAX_ROUNDS: int = int(os.environ.get("DIALOG_MAX_ROUNDS", "2"))
    BROWSER_HEADLESS: bool = bool(int(os.environ.get("BROWSER_HEADLESS", "0")))

    # 新增：窗口置顶与登录流程的可调参数
    FOCUS_WINDOW_WAIT_SEC: int = int(os.environ.get("FOCUS_WINDOW_WAIT_SEC", "2"))
    WECHAT_LOGIN_MAX_SEC: int = int(os.environ.get("WECHAT_LOGIN_MAX_SEC", "60"))
    VISUAL_SPEAK_DURING_LOGIN: bool = bool(int(os.environ.get("VISUAL_SPEAK_DURING_LOGIN", "0")))
    # 微信相关行为开关
    ENABLE_WCFERRY_LOGIN: bool = bool(int(os.environ.get("ENABLE_WCFERRY_LOGIN", "0")))
    ENABLE_WCFERRY_SEND: bool = bool(int(os.environ.get("ENABLE_WCFERRY_SEND", "0")))
    ENABLE_WECHAT_CONTACT_SYNONYMS: bool = bool(int(os.environ.get("ENABLE_WECHAT_CONTACT_SYNONYMS", "0")))
    ENABLE_WECHAT_DIRECT_SHORTCUT: bool = bool(int(os.environ.get("ENABLE_WECHAT_DIRECT_SHORTCUT", "0")))

    @classmethod
    def ensure_dirs(cls) -> None:
        cls.AUDIO_DIR.mkdir(parents=True, exist_ok=True)
        cls.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)


# Visual automation settings
VISUAL_ENABLE: bool = bool(int(os.environ.get("VISUAL_ENABLE", "1")))
VISUAL_ENGINE: str = os.environ.get("VISUAL_ENGINE", "aliyun").lower()
if VISUAL_ENGINE not in ("aliyun", "local"):
    VISUAL_ENGINE = "aliyun"

# Aliyun (DashScope compatible-mode) vision configuration
ALIYUN_BASE_URL: str = os.getenv("OPENAI_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
ALIYUN_VISION_MODEL: str = os.getenv("ALIYUN_VISION_MODEL", "qwen-vl-ocr-1028")
DASHSCOPE_API_KEY: str = os.getenv("DASHSCOPE_API_KEY", "sk-111bc08847744591bbd47bb9d3b804d5")

# Vision runtime parameters
CV_OCR_FALLBACK: bool = bool(int(os.environ.get("CV_OCR_FALLBACK", "1")))  # use local OCR when remote fails
CV_CLICK_RETRY: int = int(os.environ.get("CV_CLICK_RETRY", "2"))       # retries for click actions on detection
CV_SEARCH_TIMEOUT_SEC: int = int(os.environ.get("CV_SEARCH_TIMEOUT_SEC", "6"))
CV_SAMPLE_DOWNSCALE: float = float(os.environ.get("CV_SAMPLE_DOWNSCALE", "1.0"))  # downscale screenshot for faster inference (1.0 = no downscale)

# Approval and dialog settings
REQUIRE_APPROVAL: bool = bool(int(os.environ.get("REQUIRE_APPROVAL", "0")))
DIALOG_MAX_ROUNDS: int = int(os.environ.get("DIALOG_MAX_ROUNDS", "2"))
BROWSER_HEADLESS: bool = bool(int(os.environ.get("BROWSER_HEADLESS", "0")))

# Ensure directories exist when module is imported
Config.ensure_dirs()